package com.x.schedule.controller;

import com.x.schedule.pojo.SysUser;
import com.x.schedule.service.SysUserService;
import com.x.schedule.service.impl.SysUserServiceImpl;
import com.x.schedule.util.MD5Util;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

/**
 * ClassName: SysUserController
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.08.26 15:30
 */
@WebServlet("/user/*")
public class SysUserController extends BaseController {

    private SysUserService userService = new SysUserServiceImpl();

    /**
     * 接受注册请求的方法（业务处理接口-前后端业务接口，非java interface）
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1 接受客户端提交的参数
        String username = req.getParameter("username");
        String userPwd = req.getParameter("userPwd");

        //2 调用服务层方法，完成注册
            //把参数放入一个sysUser对象中，再调用regist方法传入service
        SysUser sysUser = new SysUser(null, username, userPwd);
        int ifRegist = userService.regist(sysUser);

        //3 根据结果页面跳转
        if(ifRegist > 0)
            resp.sendRedirect("/registSuccess.html");
        else
            resp.sendRedirect("/registFail.html");
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String userPwd = req.getParameter("userPwd");


        SysUser loginUser = userService.findUserName(username);

        if(loginUser==null)
            resp.sendRedirect("/loginUsernameError.html");
        else if(!MD5Util.encrypt(userPwd).equals(loginUser.getUserPwd()))
            resp.sendRedirect("/loginUserPwdError.html");
        else{
            //跳转登录成功之前，将登录的用户对象SysUser放入Session域
            HttpSession session = req.getSession();
            session.setAttribute("sysUser", loginUser);

            resp.sendRedirect("/showSchedule.html");
        }



    }
}
